#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-03-29 18:33:36
# @Author  : Gtlions Lai (gtlions.l@qq.com)
# @Link    : http://blog.csdn.net/gtlions
# @Version : 1.0.0
"""summarization ahout this script.

detail ahout this script

    Class(): summarization about Class
    ...
    function(): summarization about function
    ...
"""
import os, sys, paramiko


with open('/root/password.csv', 'r') as f:
    lines = f.readlines()
#for line in lines:
#    print line.split(',')[0], line.split(',')[1]
k = list(map(lambda x:(x.split(',')[0]).strip(), lines))
v = list(map(lambda x:(x.split(',')[2]).strip(), lines))
d = dict(zip(k, v))

def ssh2(ip, username, password, cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, 22, username, password, timeout=5)
        print "-----------------------execute start-----------------------"
        for m in cmd:
            stdin, stdout, stderr = ssh.exec_command(m)
            out = stdout.readlines()
            for o in out:
                print o,
        print "-----------------------execute end-------------------------"
        print '%s\tOK\n' % (ip)
        ssh.close()
    except:
        print '%s\tError\n' %(ip)

if __name__ == '__main__':
    with open('/root/.ssh/id_rsa.pub', 'r') as f:
        id_rsa=f.readlines()
    cmd = ['echo '+ id_rsa + '>> /root/.ssh/authorized_keys']
    username = 'root'
    print 'Begin......'
    for i in d:
        ssh2(i, username, d[i], cmd)
